import { userQuery, userDel, userAdd } from "../model/userModel";

export default {
  namespaced: true,
  state: {
    num: 1,
    list: [{ id: 1 }, { id: 2 }],
  },
  mutations: {
    addNum(state, n) {
      state.num = state.num + n;
    },
    addListItem(state, payload) {
      state.list.push(payload); //payload是一个对象
    },
    initList(state, list) {
      state.list = list;
    },
    delListById(state, id) {
      state.list = state.list.filter((item) => item.id != id);
    },
  },
  actions: {
    addListItem({ commit }, payload) {
        // eslint-disable-next-line
      return new Promise(async (resolve) => {
        let res2 = await userQuery({
          username: payload.username,
        });
        if (res2.data.length) {
          //有就报错
          resolve({
            code: 203,
            msg: "该用户名已经存在",
          });
        } else {
          let res = await userAdd(payload);
          commit("addListItem", res.data);
          resolve({
            code: 200,
            msg: "新增成功",
          });
        }
      });
    },
    // addListItem({ commit }, payload) {
    // //Promise executor functions should not be async  no-async-promise-executor
    //   return new Promise( (resolve) => {
    //     (async ()=>{
    //         let res2 = await userQuery({
    //             username: payload.username,
    //           });
    //           if (res2.data.length) {
    //             //有就报错
    //             resolve({
    //               code: 203,
    //               msg: "该用户名已经存在",
    //             });
    //           } else {
    //             let res = await userAdd(payload);
    //             commit("addListItem", res.data);
    //             resolve({
    //               code: 200,
    //               msg: "新增成功",
    //             });
    //           }

    //     })()

    //   });
    // },
    async initList({ commit }, params) {
      let res = await userQuery(params);
      commit("initList", res.data);
    },
    async delListById({ commit }, id) {
      await userDel(id);
      commit("delListById", id);
    },

    addNum({ commit }, n) {
      setTimeout(() => {
        commit("addNum", n);
      }, 500);
    },
  },
};
